package com.mymaxis.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import com.checkfree.isolutions.persist.*;
import com.checkfree.isolutions.streaming.*;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.persist.*;



public class GetPdfBill_WS {
	
	private static String merchant = "Maxis";
	
	public DataHandler getPdfFile(String strStmtId) throws Exception{

		//com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();
		
		System.out.println("123");
		PersistServer.activate(merchant);
		System.out.println("Activating Persistent Server.....");
        
        PersistServer.beginTransaction();
        System.out.println("Starting the transaction.....");
        
        InputStream instr   = null;
        FileOutputStream outstr = null;
      
        int statementId = Integer.parseInt(strStmtId);
        String pdfFileName = strStmtId+".pdf";
        
        File file = File.createTempFile(pdfFileName, ".pdf");
        file.deleteOnExit();
        
        try{
        StatementHome home = StatementHomeImpl.singleton();
        ObjectId objectId = new ObjectId(IClassId.STATEMENT, statementId);
        Statement cfiStatement   = home.findByObjectId(objectId);

        outstr = new FileOutputStream(file);
        
        byte[] buffer = new byte[262144];
        int size = 0;
        instr = cfiStatement.getExternalFormatData();

		while ((size  = instr.read(buffer, 0, buffer.length)) != -1) {
			outstr.write(buffer, 0, size);
		}
		instr.close();
		outstr.flush();
		outstr.close();
 	    PersistServer.commitTransaction();

        }  catch (Exception ex) {
            System.err.println(ex.getMessage());
            ex.printStackTrace();
            if (PersistServer.transactionIsActive()){
				try {
					PersistServer.rollbackTransaction();
				}catch (Exception e) {
				}
			}
			PersistServer.deactivate(); //clean up with deactivate
        }
        javax.activation.DataHandler dataHandler = new javax.activation.DataHandler(new FileDataSource(file));
		return dataHandler;
	}
	
//	public static void main(String[] args){
//		GetPdfBill_WS web = new GetPdfBill_WS();
//		try{
//			OutputStream op = new FileOutputStream("D:\\test1234.pdf");
//			javax.activation.DataHandler data = web.getPdfFile("95001");
//			data.writeTo(op);
//			
//		}catch(Exception e){
//			e.printStackTrace();
//		}
//
//	}
}
